package com.louis.iread.skin;

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.louis.iread.bean.Config;
import com.louis.iread.event.EventType;
import com.louis.iread.event.ReadEvent;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by louis on 17-8-29.
 */

public class SkinMgr {
    private static final String TAG = SkinMgr.class.getName();

    private static String mSkin = ""; //皮肤名称
    private static Context mContext;    //上下文
    private List<ActivityItem> mActivities; //activity列表
    private ResourceManager mResourceManager;
    private static SkinMgr mSkinMgr;
    public static SkinMgr getInstance() {
        if (mSkinMgr == null) {
            mSkinMgr = new SkinMgr();
        }
        return mSkinMgr;
    }

    public void switchReadMode() {
        String theme = Config.getTheme();
        if (theme.equals(Config.DAY)) {
            Config.setTheme(Config.NIGHT);
            SkinMgr.getInstance().changeSkin(Config.getTheme());
            EventBus.getDefault().post(new ReadEvent(EventType.SWITCH_TO_NIGHT));
        } else {
            Config.setTheme(Config.DAY);
            SkinMgr.getInstance().changeSkin(Config.getTheme());
            EventBus.getDefault().post(new ReadEvent(EventType.SWTCH_TO_DAY));
        }
    }

    public void init(Context context)
    {
        mContext = context;
        if (mActivities == null) {
            mActivities = new ArrayList<>();
        }
    }

    public static String getTheme() {
        return mSkin;
    }

    public ResourceManager getResourceManager()
    {
        if (mResourceManager == null)
        {
            mResourceManager = new ResourceManager(mContext, mContext.getResources(), mContext.getPackageName(), mSkin);
        }
        return mResourceManager;
    }

    public void changeSkin(String skin) {
        if (skin == null) {
            if ("".equals(mSkin)) {
                return;
            }
            mSkin = "";
        } else if (skin.equals(mSkin)){
            return;
        } else {
            mSkin = skin;
        }
        mResourceManager = new ResourceManager(mContext, mContext.getResources(), mContext.getPackageName(), mSkin);
        notifyChangeAll();
    }

    public void register(final Activity activity) {
        if (activity == null) {
            return;
        }
        ActivityItem item = null;
        for(ActivityItem activityItem : mActivities) {
            if (activity == activityItem.mActivity) {
                item = activityItem;
            }
        }

        if (item == null) {
            item = new ActivityItem();
            item.mActivity = activity;
            mActivities.add(item);
        }
        item.mReferNum++;
        ViewGroup content = (ViewGroup) activity.findViewById(android.R.id.content);
        ActivityItem finalItem = item;
        content.post(new Runnable() {
            @Override
            public void run() {
                notifyChange(finalItem);
            }
        });
    }

    public void unregister(Activity activity) {
        if (activity == null) {
            return;
        }

        ActivityItem willRemove = null;
        for (ActivityItem item : mActivities) {
            if (activity == item.mActivity) {
                item.mReferNum--;
                if (item.mReferNum <= 0) {
//                    mActivities.remove(item);
                    willRemove = item;
                }
                break;
            }
        }
        if (willRemove != null) {
            mActivities.remove(willRemove);
        }
    }

    public void notifyChangeAll() {
        for (ActivityItem item : mActivities) {
            apply(item.mActivity);
            if (item.mActivity instanceof SkinChangeCallback) {
                SkinChangeCallback callback = (SkinChangeCallback) item.mActivity;
                callback.onSkinChange(mSkin);
            }
        }
    }

    public void notifyChange(ActivityItem item) {
        if (item != null && item.mActivity != null) {
            apply(item.mActivity);
            if (item.mActivity instanceof SkinChangeCallback) {
                SkinChangeCallback callback = (SkinChangeCallback) item.mActivity;
                callback.onSkinChange(mSkin);
            }
        }
    }

    protected void apply(Activity activity) {
        if (activity == null) {
            return;
        }
        ViewGroup content = (ViewGroup) activity.findViewById(android.R.id.content);
        applyView(content);
    }

    public void applyView(View view) {
        if (view instanceof TextView) {
            TextView textView = (TextView) view;
//            Log.i(TAG, textView.getText().toString());
        }
        if (view instanceof ViewGroup) {
            ViewGroup container = (ViewGroup) view;
            for (int i = 0, n = container.getChildCount(); i < n; i++)
            {
                View child = container.getChildAt(i);
                applyView(child);
            }
        }
        changeViewSkin(view);
    }

    protected void changeViewSkin(View view) {
        Object tag = view.getTag();
        if (tag == null) {
//            Log.d(TAG, "tag is null");
            return;
        }
//        Log.d(TAG, tag.getClass().getName());
        if (!(tag instanceof String)) {
//            Log.d(TAG, "tags is not String");
            return;
        }

        String strTag = (String) tag;
//        Log.i(TAG, "===========================" + strTag);
        List<SkinAttr> skinAttrs = parseTag(strTag);
        if (!skinAttrs.isEmpty())
        {
            for (SkinAttr attr : skinAttrs)
            {
                attr.apply(view);
            }
        }
    }

    //skin:left_menu_icon:src|skin:color_red:textColor
    private static List<SkinAttr> parseTag(String tagStr)
    {
        List<SkinAttr> skinAttrs = new ArrayList<SkinAttr>();
        if (TextUtils.isEmpty(tagStr)) return skinAttrs;

        String[] items = tagStr.split("[|]");
        for (String item : items)
        {
            if (!item.startsWith(SkinConfig.SKIN_PREFIX))
                continue;
            String[] resItems = item.split(":");
            if (resItems.length != 3)
                continue;

            String resName = resItems[1];
            String resType = resItems[2];

            SkinAttrType attrType = getSupportAttrType(resType);
            if (attrType == null) continue;
            SkinAttr attr = new SkinAttr(attrType, resName);
            skinAttrs.add(attr);
        }
        return skinAttrs;
    }

    private static SkinAttrType getSupportAttrType(String attrName)
    {
        for (SkinAttrType attrType : SkinAttrType.values())
        {
            if (attrType.getAttrType().equals(attrName))
                return attrType;
        }
        return null;
    }
}

class ActivityItem {
    public int mReferNum = 0;   //引用统计
    public Activity mActivity;
    public ActivityItem() {
        mReferNum = 0;
        mActivity = null;
    }
}